package global_village.gui;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import global_village.app.Settings;
import global_village.app.Utils;
import global_village.data.Group;
import global_village.data.ServerRequest;
import global_village.data.utils.AsyncHttpQuery;
import global_village.gui.utils.GroupsAdapter;
import global_village.gui.utils.StatusListener;
import android.app.Activity;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.view.ViewPager.LayoutParams;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.global_village.app.R;
import static global_village.data.Constants.*;


public class Main extends Activity {

	private static final String TAG = Main.class.getSimpleName();
	
	private Button btnCreateGroup;
	private Button btnFindGroup;
	
	private GridView gvGroups;
	private GroupsAdapter groupsAdpter;
	
	private RelativeLayout rlStatus;

	private LocationManager lm;
	private String bestProvider;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	Log.v(TAG, "< OnCreate >");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initGui();
        lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    }
    
	/**
     * Initialize GUI components.
     * @author Noam Tzumie
     */
    private void initGui(){
    	btnCreateGroup = (Button) findViewById(R.id.main_btn_create_group);
    	btnFindGroup = (Button) findViewById(R.id.main_btn_find_groups);
    	gvGroups = (GridView) findViewById(R.id.main_grid_groups);
    	rlStatus = (RelativeLayout) findViewById(R.id.main_rl_download_status);
    	
    	btnCreateGroup.setOnClickListener(createGroupLis());
    	btnFindGroup.setOnClickListener(findGroupLis());
    	gvGroups.setOnItemClickListener(gvItemLis());
    }
    private OnItemClickListener gvItemLis(){
    	return new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				Intent intent = new Intent(Main.this , Room.class);
				//TODO - move to constant
				intent.putExtra(GROUP_TYPE, groupsAdpter.getItem(position).getType());
				startActivity(intent);
			}
    		
		};
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
		case R.id.menu_settings:
			startActivity(new Intent(this, Settings.class));
			break;

		case R.id.menu_refresh:
			Log.e(TAG, "unimlemented method detected");
			break;
		}
		return super.onContextItemSelected(item);
    }
    
    
    /**
     * Handle the click event of create group button
     * @return OnClickListener
     * @author Noam Tzumie
     */
    private OnClickListener createGroupLis(){
    	return new OnClickListener() {
			
			public void onClick(View v) {
//				Log.e(TAG, "unimlemented method detected");
//				AsyncHttpQuery task = new AsyncHttpQuery();
//				task.setOnStatusListener(stautsLis());
//				// DEBUG //
//				String serverIp = Utils.getSettingsByKey("serverIp");
//				Log.w(TAG, "The server IP is: " + serverIp);
//				task.execute(new ServerRequest("POST","http://" + serverIp + "/getData.inc.php","1287.154315345340"));
				
				startActivity(new Intent(Main.this, CreateGroup.class));
			}
		};
    }
    /**
     * Handle the click event of find group button
     * @return OnClickListener
     * @author Noam Tzumie
     */
    private OnClickListener findGroupLis(){
    	return new OnClickListener() {
			
			public void onClick(View v) {
				AsyncHttpQuery task = new AsyncHttpQuery();
				task.setOnStatusListener(stautsLis());
				// DEBUG //
				String serverIp = Utils.getSettingsByKey("serverIp");
				Log.w(TAG, "The server IP is: " + serverIp);
				task.execute(new ServerRequest("GET","http://" + serverIp + "/getData.inc.php",null));
			}
		};
    }
    
    private StatusListener stautsLis(){
    	return new StatusListener() {
			
    		/**
			 * Showing the relative layout that holds the spinner ant the text view.
			 * @author Noam Tzumie
			 */
			public void showStatus(String message) {
				Log.i("StatusListener", "< showStatus >");
				//TODO - this is a hack need to fix.
				ViewGroup.LayoutParams lp = rlStatus.getLayoutParams();
				lp.width = LayoutParams.FILL_PARENT;
				lp.height = LayoutParams.WRAP_CONTENT;
				rlStatus.setLayoutParams(lp);
				TextView tv = (TextView) rlStatus.getChildAt(1);
				tv.setText(message);
			}
			/**
			 * Hiding the relative layout that holds the spinner ant the text view.
			 * @author Noam Tzumie
			 */
			public void hideStatus() {
				Log.i("StatusListener", "< hideStatus >");
				//TODO - this is a hack need to fix.
				ViewGroup.LayoutParams lp = rlStatus.getLayoutParams();
				lp.height = 0;
				rlStatus.setLayoutParams(lp);
				
			}
			public void processJson(String json) {
				Log.i(TAG, "< processJson >");
				// TODO remove this method
				Log.w(TAG, "the json is:"+json);
				ArrayList<Group> groups = new ArrayList<Group>();
				try {
					JSONArray array = new JSONArray(json);
					for(int i=0; i<array.length(); i++){
						groups.add(new Group(array.getJSONObject(i)));
					}
				} catch (Exception e) {
					Log.e(TAG, e.toString());
				}
				Log.w(TAG, "num items: " + groups.size());
				groupsAdpter = new GroupsAdapter(Main.this, groups);
				gvGroups.setAdapter(groupsAdpter);
				groupsAdpter.notifyDataSetChanged();
			}
		};
    }
}
